package org.example.tialsproject.Interceptor;

import com.alibaba.fastjson.JSONObject;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.tialsproject.pojo.ResponseResult;
import org.example.tialsproject.utils.JwtUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
public class DemoInterceptor implements HandlerInterceptor {
    /*目标资源方法运行前运行 ,返回true就放行,返回false不放行 */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURI();
        if (url.contains("/user/login")) {
            /*放行本次请求*/
            return true;
        } else {
            String jwt = request.getHeader("token");
            if (!StringUtils.hasLength(jwt)) {
                ResponseResult error = ResponseResult.error("请登录");
                String jsonString = JSONObject.toJSONString(error);
                response.getWriter().write(jsonString);
                return false;
            } else {
                try {
                    JwtUtils.parseJwt(jwt);
                    return true;
                } catch (Exception e) {
                    ResponseResult error = ResponseResult.error("请登录");
                    String jsonString = JSONObject.toJSONString(error);
                    response.getWriter().write(jsonString);
                    return false;
                }
            }
        }
    }

    /*目标资源方法运行后运行*/
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

    /*视图渲染完毕后运行,最后运行*/
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }
}
